import classNames from 'classnames';
import React from 'react';
import { CollapseSetValueType, CollapseValueType } from './collapse';

export type CollapseItemNameType = string | number | undefined;
export type CollapseItemTitleType = string | number | undefined;

export interface CollapseItemProps {
    isOpen?: boolean
    name: CollapseItemNameType
    title?: CollapseItemTitleType
    titleJSX?: React.ReactNode
    children?: React.ReactNode
    className?: string
    style?: React.CSSProperties
    value?: CollapseValueType
    setValue?: CollapseSetValueType
    accordion?: boolean
}

const CollapseItem: React.FC<CollapseItemProps> = props => {

    const { name, isOpen, title, titleJSX, children, className, style, accordion, setValue, value } = props;

    // title点击效果
    const titleContainerClick = () => {
        console.log(isOpen, accordion);
        if (isOpen) {
            if (accordion) {
                if (setValue) {
                    setValue(undefined)
                }
            } else {
                if (value instanceof Array && setValue) {
                    setValue(value.filter(
                        (item) => item !== name
                    ))
                }
            }
        } else {
            if (accordion) {
                if (setValue) {
                    setValue(name)
                }
            } else {
                if (value instanceof Array && setValue) {
                    setValue([...value, name])
                }
            }
        }
    }

    const classes = classNames(className, "packages-yulang-collapse-item-container");

    const renderTitle = () => {
        return titleJSX ? titleJSX : title
    }

    return <div className={classes} style={style}>
        <div
            className={"yulang-collapse-item-title-container"}
            onClick={titleContainerClick}
        >
            <div className={"title"}>
                {renderTitle()}
            </div>
            {isOpen ? <i className={"iconfont icon-chevron-down"}></i> : <i className={"iconfont icon-chevron-right"}></i>}
        </div>
        {isOpen ? <div className={"yulang-collapse-item-content"}>
            {children}
        </div> : <></>}
    </div >
}

CollapseItem.defaultProps = {
    isOpen: false
}

CollapseItem.displayName = "CollapseItem"

export default CollapseItem;